<template>
  <el-dropdown @command="handleCommand" trigger="click" placement="bottom-end">
    <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
      <el-button type="text" class="notification-button">
        <el-icon size="20">
          <Bell />
        </el-icon>
      </el-button>
    </el-badge>
    
    <template #dropdown>
      <div class="notification-dropdown">
        <div class="notification-header">
          <span class="title">消息通知</span>
          <div class="actions">
            <el-button type="text" size="small" @click="markAllAsRead" :disabled="unreadCount === 0">
              全部已读
            </el-button>
            <el-button type="text" size="small" @click="showSettings">
              设置
            </el-button>
          </div>
        </div>
        
        <div class="notification-content">
          <div v-if="messages.length === 0" class="empty-state">
            <el-icon size="48" color="#c0c4cc"><Bell /></el-icon>
            <p>暂无消息</p>
          </div>
          
          <div v-else class="message-list">
            <div 
              v-for="message in displayMessages" 
              :key="message.id"
              class="message-item"
              :class="{ 'unread': !message.isRead, 'high-priority': message.priority === 'high' }"
              @click="handleMessageClick(message)"
            >
              <div class="message-icon">
                <el-icon :color="getMessageIconColor(message.type)">
                  <component :is="getMessageIcon(message.type)" />
                </el-icon>
              </div>
              
              <div class="message-content">
                <div class="message-title">
                  <span>{{ message.title }}</span>
                  <el-tag 
                    v-if="message.priority === 'high'" 
                    type="danger" 
                    size="small"
                  >
                    紧急
                  </el-tag>
                </div>
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.createTime) }}</div>
              </div>
              
              <div class="message-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="deleteMessage(message.id)"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div class="notification-footer">
          <el-button type="text" @click="viewAllMessages">查看全部消息</el-button>
        </div>
      </div>
    </template>
  </el-dropdown>

  <!-- 消息详情对话框 -->
  <el-dialog
    v-model="messageDialogVisible"
    title="消息详情"
    width="600px"
  >
    <div v-if="selectedMessage" class="message-detail">
      <div class="message-header">
        <div class="message-title">
          <h3>{{ selectedMessage.title }}</h3>
          <el-tag 
            :type="getPriorityTagType(selectedMessage.priority)"
            size="small"
          >
            {{ getPriorityText(selectedMessage.priority) }}
          </el-tag>
        </div>
        <div class="message-meta">
          <span class="message-type">{{ getTypeText(selectedMessage.type) }}</span>
          <span class="message-time">{{ selectedMessage.createTime }}</span>
        </div>
      </div>
      
      <div class="message-body">
        <p>{{ selectedMessage.content }}</p>
      </div>
      
      <div v-if="selectedMessage.orderId" class="message-actions">
        <el-button type="primary" @click="handleOrderAction(selectedMessage)">
          查看订单
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 通知设置对话框 -->
  <el-dialog
    v-model="settingsDialogVisible"
    title="通知设置"
    width="500px"
  >
    <el-form :model="settings" label-width="120px">
      <el-form-item label="桌面通知">
        <el-switch v-model="settings.enableDesktop" />
        <div class="form-tip">在桌面显示通知弹窗</div>
      </el-form-item>
      
      <el-form-item label="声音提醒">
        <el-switch v-model="settings.enableSound" />
        <div class="form-tip">收到消息时播放提示音</div>
      </el-form-item>
      
      <el-form-item label="邮件通知">
        <el-switch v-model="settings.enableEmail" />
        <div class="form-tip">通过邮件发送重要通知</div>
      </el-form-item>
      
      <el-divider>通知类型</el-divider>
      
      <el-form-item label="系统通知">
        <el-switch v-model="settings.types.system" />
      </el-form-item>
      
      <el-form-item label="订单通知">
        <el-switch v-model="settings.types.order" />
      </el-form-item>
      
      <el-form-item label="库存通知">
        <el-switch v-model="settings.types.inventory" />
      </el-form-item>
      
      <el-form-item label="审批通知">
        <el-switch v-model="settings.types.approval" />
      </el-form-item>
      
      <el-form-item label="财务通知">
        <el-switch v-model="settings.types.finance" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="settingsDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveSettings">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useNotificationStore } from '@/stores/notification'

const router = useRouter()
const notificationStore = useNotificationStore()

// 响应式数据
const messageDialogVisible = ref(false)
const settingsDialogVisible = ref(false)
const selectedMessage = ref(null)

// 计算属性
const messages = computed(() => notificationStore.messages)
const unreadCount = computed(() => notificationStore.unreadCount)
const settings = computed(() => notificationStore.settings)

const displayMessages = computed(() => {
  return messages.value.slice(0, 10) // 只显示前10条消息
})

// 方法
const handleCommand = (command) => {
  // 处理下拉菜单命令
}

const handleMessageClick = (message) => {
  selectedMessage.value = message
  messageDialogVisible.value = true
  
  // 标记为已读
  if (!message.isRead) {
    notificationStore.markAsRead(message.id)
  }
}

const deleteMessage = (messageId) => {
  notificationStore.deleteMessage(messageId)
}

const markAllAsRead = () => {
  notificationStore.markAllAsRead()
  ElMessage.success('已标记所有消息为已读')
}

const showSettings = () => {
  settingsDialogVisible.value = true
}

const saveSettings = () => {
  notificationStore.updateSettings(settings.value)
  settingsDialogVisible.value = false
  ElMessage.success('设置已保存')
}

const viewAllMessages = () => {
  // 跳转到消息列表页面
  router.push('/system/notifications')
}

const handleOrderAction = (message) => {
  if (message.orderId) {
    // 跳转到订单详情页面
    router.push(`/sales/orders/${message.orderId}`)
    messageDialogVisible.value = false
  }
}

// 工具方法
const getMessageIcon = (type) => {
  const iconMap = {
    system: 'Setting',
    order: 'ShoppingCart',
    inventory: 'Box',
    approval: 'DocumentChecked',
    finance: 'Money'
  }
  return iconMap[type] || 'Bell'
}

const getMessageIconColor = (type) => {
  const colorMap = {
    system: '#409EFF',
    order: '#67C23A',
    inventory: '#E6A23C',
    approval: '#F56C6C',
    finance: '#909399'
  }
  return colorMap[type] || '#409EFF'
}

const getTypeText = (type) => {
  const typeMap = {
    system: '系统通知',
    order: '订单通知',
    inventory: '库存通知',
    approval: '审批通知',
    finance: '财务通知'
  }
  return typeMap[type] || '系统通知'
}

const getPriorityText = (priority) => {
  const priorityMap = {
    high: '高优先级',
    medium: '中优先级',
    low: '低优先级'
  }
  return priorityMap[priority] || '中优先级'
}

const getPriorityTagType = (priority) => {
  const typeMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return typeMap[priority] || 'warning'
}

const formatTime = (time) => {
  const now = new Date()
  const messageTime = new Date(time)
  const diff = now - messageTime
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return messageTime.toLocaleDateString()
  }
}

// 生命周期
onMounted(() => {
  // 请求通知权限
  notificationStore.requestNotificationPermission()
  
  // 加载设置
  notificationStore.loadSettings()
})
</script>

<style scoped>
.notification-badge {
  margin-right: 8px;
}

.notification-button {
  padding: 8px;
  color: #606266;
}

.notification-button:hover {
  color: #409EFF;
}

.notification-dropdown {
  width: 400px;
  max-height: 500px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.notification-header .title {
  font-weight: 600;
  color: #303133;
}

.notification-header .actions {
  display: flex;
  gap: 8px;
}

.notification-content {
  max-height: 350px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state p {
  margin-top: 12px;
  font-size: 14px;
}

.message-list {
  padding: 8px 0;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: background-color 0.2s;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item.unread {
  background-color: #f0f9ff;
  border-left: 3px solid #409EFF;
}

.message-item.high-priority {
  background-color: #fef0f0;
}

.message-icon {
  margin-right: 12px;
  margin-top: 2px;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.message-title span {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.message-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-time {
  color: #909399;
  font-size: 12px;
}

.message-actions {
  margin-left: 8px;
}

.notification-footer {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

.message-detail {
  padding: 20px 0;
}

.message-header {
  margin-bottom: 20px;
}

.message-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.message-title h3 {
  margin: 0;
  color: #303133;
}

.message-meta {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 14px;
}

.message-body {
  margin-bottom: 20px;
}

.message-body p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
